import api from '@/utils/api.js'

// ==================== 用户认证相关 ====================

/**
 * 用户登录
 * @param {Object} loginData - 登录数据
 * @param {string} loginData.email - 邮箱
 * @param {string} loginData.password - 密码
 */
export const userLogin = (loginData) => {
  return api.post('/user/login', loginData)
}

/**
 * 发送注册验证码
 * @param {string} email - 邮箱地址
 */
export const sendRegisterCode = (email) => {
  return api.post('/user/send-code', { email })
}

/**
 * 用户注册
 * @param {Object} registerData - 注册数据
 */
export const userRegister = (registerData) => {
  return api.post('/user/register', registerData)
}

/**
 * 管理员登录
 * @param {Object} loginData - 登录数据
 */
export const adminLogin = (loginData) => {
  return api.post('/admin/login', loginData)
}

/**
 * 获取用户信息
 */
export const getUserInfo = () => {
  return api.get('/user/info')
}

// ==================== 房源管理相关 ====================

/**
 * 获取所有房源
 */
export const getAllHouses = () => {
  return api.get('/house/selectAll')
}

/**
 * 根据条件搜索房源
 * @param {Object} condition - 搜索条件
 */
export const searchHouses = (condition) => {
  return api.post('/house/selectByCondition', condition)
}

/**
 * 搜索附近房源
 * @param {Object} request - 位置信息
 */
export const searchNearbyHouses = (request) => {
  return api.post('/house/selectNearby', request)
}

/**
 * 发布房源
 * @param {Object} houseData - 房源数据
 */
export const publishHouse = (houseData) => {
  return api.post('/landlord/publish', houseData)
}

// ==================== 房源审核相关 ====================

/**
 * 提交房源认证
 * @param {Object} verificationData - 认证数据
 */
export const submitPropertyVerification = (verificationData) => {
  return api.post('/landlord/submitVerification', verificationData)
}

/**
 * 查询房产认证状态
 * @param {string} propertyNo - 房产证编号
 */
export const getPropertyVerifyStatus = (propertyNo) => {
  return api.get(`/landlord/getPropertyVerifyStatusByPropertyNo/${propertyNo}`)
}

/**
 * 查询房产认证驳回原因
 * @param {string} propertyNo - 房产证编号
 */
export const getPropertyVerifyRefuseReason = (propertyNo) => {
  return api.get(`/landlord/getPropertyVerifyRefuseReasonByPropertyNo/${propertyNo}`)
}

/**
 * 取消房产认证
 * @param {string} propertyNo - 房产证编号
 */
export const cancelPropertyVerify = (propertyNo) => {
  return api.post(`/landlord/cancelPropertyVerify/${propertyNo}`)
}

/**
 * 根据用户ID查询房产认证信息
 * @param {number} userId - 用户ID
 */
export const getPropertyVerificationByUserId = (userId) => {
  return api.get(`/landlord/getPropertyVerificationByUserId/${userId}`)
}

/**
 * 根据房东ID查询发布的房源
 * @param {number} landlordId - 房东ID
 */
export const getHouseByUserId = (landlordId) => {
  return api.get(`/landlord/getHouseByUserId/${landlordId}`)
}

/**
 * 删除已被驳回的房源验证
 * @param {number} propertyVerifyId - 房产验证ID
 * @param {number} userId - 用户ID
 */
export const cancelVerification = (propertyVerifyId, userId) => {
  return api.post(`/landlord/cancelVerification/${userId}/${propertyVerifyId}`)
}

/**
 * 批量删除已被驳回的房源验证
 * @param {Array} propertyVerifyIds - 房产验证ID数组
 * @param {number} userId - 用户ID
 */
export const cancelBatchVerification = (propertyVerifyIds, userId) => {
  return api.post(`/landlord/cancelBatchVerification/${userId}`, propertyVerifyIds)
}

/**
 * 获取用户发布的房源
 */
export const getMyHouses = () => {
  return api.get('/landlord/findHouseByUserId')
}

/**
 * 获取房源详情
 * @param {number} houseId - 房源ID
 */
export const getHouseDetail = (houseId) => {
  return api.get(`/house/detail/${houseId}`)
}

/**
 * 房东根据房产ID查询房产信息
 * @param {number} houseId - 房源ID
 */
export const getHouseByHouseId = (houseId) => {
  return api.get(`/landlord/getHouseByHouseId/${houseId}`)
}

/**
 * 更新房源信息
 * @param {Object} houseInfoUpdateRequest - 房源更新信息
 */
export const updateHouseInfo = (houseInfoUpdateRequest) => {
  return api.post('/landlord/updateHouseInfo', houseInfoUpdateRequest)
}

/**
 * 更新配套设施信息
 * @param {number} houseId - 房源ID
 * @param {Object} complementaryFacilities - 配套设施信息
 */
export const updateComplementaryFacilities = (houseId, complementaryFacilities) => {
  return api.post(`/landlord/updateComplementaryFacilities/${houseId}`, complementaryFacilities)
}

/**
 * 更新房源状态（上架/下架）
 * @param {number} houseId - 房源ID
 * @param {number} houseStatus - 房源状态（0=上架重新为待出租状态，2=下架）
 */
export const updateHouseStatus = (houseId, houseStatus) => {
  return api.post(`/landlord/updateHouseStatus/${houseId}?houseStatus=${houseStatus}`)
}

// ==================== 中介相关 ====================

/**
 * 申请成为中介
 * @param {Object} applyData - 申请数据
 */
export const applyAgent = (applyData) => {
  return api.post('/agent/auth/apply', applyData)
}

/**
 * 获取中介申请结果
 */
export const getAgentApplyResult = () => {
  return api.get('/agent/auth/result')
}

/**
 * 获取所有可代理房源
 */
export const getAllAgentRentalHouses = () => {
  return api.get('/agent-rental/getAllAgentRentalHouse')
}

/**
 * 获取中介代理的房源
 */
export const getAgentHouses = () => {
  return api.get('/agent-rental/getAllAgentHouse')
}

// ==================== 预约相关 ====================

/**
 * 提交预约申请
 * @param {Object} appointmentData - 预约数据
 */
export const submitAppointment = (appointmentData) => {
  return api.post('/appointment', appointmentData)
}

/**
 * 获取用户的预约列表
 */
export const getUserAppointments = () => {
  return api.get('/appointment/user')
}

/**
 * 根据租客ID获取预约列表
 * @param {number} tenantId - 租客ID
 */
export const getTenantAppointments = (tenantId) => {
  return api.get(`/appointment/list/${tenantId}`)
}

/**
 * 获取房东的预约列表
 */
export const getLandlordAppointments = () => {
  return api.get('/appointment/landlord')
}

/**
 * 获取中介的预约列表
 */
export const getAgentAppointments = () => {
  return api.get('/appointment/agent')
}

/**
 * 更新预约状态
 * @param {number} appointmentId - 预约ID
 * @param {string} status - 状态 (confirmed/rejected)
 * @param {string} reason - 原因
 */
export const updateAppointmentStatus = (appointmentId, status, reason = '') => {
  return api.put(`/appointment/${appointmentId}/status`, { status, reason })
}

// ==================== 租房流程相关 ====================

/**
 * 租客发起签约申请
 * @param {Object} contractData - 合同数据
 */
export const applyContract = (contractData) => {
  return api.post('/contract/tenant/apply', contractData)
}

/**
 * 获取租客合同列表
 */
export const getTenantContracts = () => {
  return api.get('/contract/tenant/list')
}

/**
 * 获取房东合同列表
 */
export const getLandlordContracts = () => {
  return api.get('/contract/landlord/list')
}

// ==================== 管理员相关 ====================

/**
 * 获取待审核中介列表
 */
export const getPendingAgents = () => {
  return api.get('/admin/agent/pending')
}

/**
 * 获取所有房产认证信息
 */
export const getAllPropertyVerification = () => {
  return api.get('/admin/house/getAllPropertyVerification')
}

/**
 * 管理员通过房产信息认证
 * @param {number} propertyVerifyId - 房产认证ID
 */
export const passPropertyVerify = (propertyVerifyId) => {
  return api.post(`/admin/house/passVerify/${propertyVerifyId}`)
}

/**
 * 管理员批量通过房产信息认证
 * @param {Array} propertyVerifyIds - 房产认证ID数组
 */
export const batchPassPropertyVerify = (propertyVerifyIds) => {
  return api.post('/admin/house/batchPassVerify', propertyVerifyIds)
}

/**
 * 管理员驳回房产信息认证
 * @param {number} propertyVerifyId - 房产认证ID
 * @param {string} reason - 拒绝原因
 */
export const rejectPropertyVerification = (propertyVerifyId, reason) => {
  return api.post(`/admin/house/rejectPropertyVerification/${propertyVerifyId}`, reason, {
    headers: {
      'Content-Type': 'text/plain'
    }
  })
}

/**
 * 审核中介申请
 * @param {number} agentId - 中介ID
 * @param {string} status - 审核状态 (approved/rejected)
 * @param {string} reason - 审核原因
 */
export const reviewAgent = (agentId, status, reason) => {
  return api.post('/admin/agent/review', { agentId, status, reason })
}

/**
 * 获取待审核房源列表
 */
export const getPendingHouses = () => {
  return api.get('/admin/house/pending')
}

/**
 * 审核房源
 * @param {number} houseId - 房源ID
 * @param {string} status - 审核状态
 * @param {string} reason - 审核原因
 */
export const reviewHouse = (houseId, status, reason) => {
  return api.post('/admin/house/review', { houseId, status, reason })
}

/**
 * 获取用户列表
 * @param {Object} params - 查询参数
 */
export const getUserList = (params) => {
  return api.get('/admin/user/list', { params })
}

/**
 * 获取系统统计数据
 */
export const getSystemStats = () => {
  return api.get('/admin/stats')
}

// ==================== 消息相关 ====================

/**
 * 创建或获取聊天会话
 * @param {Object} sessionData - 会话数据
 * @param {number} sessionData.targetUserId - 目标用户ID
 * @param {number} sessionData.houseId - 房源ID (可选)
 */
export const createChatSession = (sessionData) => {
  return api.post('/message/create-session', sessionData)
}

/**
 * 获取用户的聊天会话列表
 */
export const getChatSessions = () => {
  return api.get('/message/sessions')
}

/**
 * 获取会话的消息历史
 * @param {number} sessionId - 会话ID
 * @param {Object} params - 查询参数
 * @param {number} params.page - 页码 (默认1)
 * @param {number} params.size - 每页大小 (默认20)
 */
export const getSessionMessages = (sessionId, params = {}) => {
  return api.get(`/message/session/${sessionId}`, { params })
}

/**
 * 发送消息 (REST API方式)
 * @param {Object} messageData - 消息数据
 * @param {number} messageData.receiverId - 接收者ID
 * @param {number} messageData.houseId - 房源ID (可选)
 * @param {string} messageData.content - 消息内容
 * @param {number} messageData.type - 消息类型 (可选)
 */
export const sendChatMessage = (messageData) => {
  return api.post('/message/send', messageData)
}

/**
 * 标记消息为已读
 * @param {number} sessionId - 会话ID
 */
export const markMessagesAsRead = (sessionId) => {
  return api.post('/message/read', { sessionId })
}

/**
 * 获取会话未读消息数量
 * @param {number} sessionId - 会话ID
 */
export const getSessionUnreadCount = (sessionId) => {
  return api.get(`/message/unread/${sessionId}`)
}

/**
 * 获取用户总未读消息数量
 */
export const getTotalUnreadCount = () => {
  return api.get('/message/unread/total')
}

/**
 * 搜索用户（用于发起聊天）
 * @param {string} keyword - 搜索关键词
 */
export const searchUsers = (keyword) => {
  return api.get('/user/search', { params: { keyword } })
}

// ==================== 兼容性API (保留旧接口) ====================

/**
 * 获取消息列表 (兼容性接口)
 * @param {Object} params - 查询参数 (暂未使用)
 */
export const getMessages = (params = {}) => {
  // 忽略params参数，直接返回会话列表
  return getChatSessions()
}

/**
 * 获取聊天记录 (兼容性接口)
 * @param {number} sessionId - 会话ID
 * @param {Object} params - 查询参数
 */
export const getChatHistory = (sessionId, params = {}) => {
  return getSessionMessages(sessionId, params)
}

/**
 * 发送消息 (兼容性接口)
 * @param {Object} messageData - 消息数据
 */
export const sendMessage = (messageData) => {
  return sendChatMessage(messageData)
}

/**
 * 批量标记消息为已读 (兼容性接口)
 * @param {Array} messageIds - 消息ID数组
 */
export const markMessagesRead = (messageIds) => {
  return api.post('/message/read/batch', { messageIds })
}

/**
 * 标记单个消息为已读 (兼容性接口)
 * @param {number} messageId - 消息ID
 */
export const markMessageRead = (messageId) => {
  return api.post(`/message/read/${messageId}`)
}

/**
 * 获取未读消息数量 (兼容性接口)
 */
export const getUnreadCount = () => {
  return getTotalUnreadCount()
}

// ==================== 系统消息相关 ====================

/**
 * 获取系统消息列表
 * @param {Object} params - 查询参数
 * @param {number} params.page - 页码 (默认1)
 * @param {number} params.size - 每页大小 (默认20)
 * @param {string} params.type - 消息类型 (可选)
 */
export const getSystemMessages = (params = {}) => {
  return api.get('/message/system/list', { params })
}

/**
 * 标记系统消息为已读
 * @param {number} messageId - 消息ID
 */
export const markSystemMessageRead = (messageId) => {
  return api.post(`/message/system/read/${messageId}`)
}

/**
 * 批量标记系统消息为已读
 * @param {Array} messageIds - 消息ID数组
 */
export const markSystemMessagesRead = (messageIds) => {
  return api.post('/message/system/read/batch', { messageIds })
}

/**
 * 删除系统消息
 * @param {number} messageId - 消息ID
 */
export const deleteSystemMessage = (messageId) => {
  return api.delete(`/message/system/${messageId}`)
}

/**
 * 获取系统消息未读数量
 */
export const getSystemUnreadCount = () => {
  return api.get('/message/system/unread/count')
}

// ==================== 文件上传相关 ====================

/**
 * 上传图片到OSS
 * @param {FormData} formData - 图片数据
 */
export const uploadImage = (formData) => {
  return api.post('/oss/upload/propertyImages', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
}

/**
 * 上传PDF文件到OSS
 * @param {FormData} formData - PDF文件数据
 */
export const uploadPdf = (formData) => {
  return api.post('/oss/upload/contractPDfs', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
}

/**
 * 上传通用文件到OSS
 * @param {FormData} formData - 文件数据
 * @param {string} folder - 文件夹名称（可选）
 */
export const uploadFile = (formData, folder = 'files/') => {
  if (folder && !formData.has('folder')) {
    formData.append('folder', folder)
  }
  return api.post('/oss/upload/file', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
}
